package com.cheyunkeji.er.fragment.evaluate;

import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.activity.evaluate.EvaluateWorkflowActivity;
import com.cheyunkeji.er.base.BaseFragment;
import com.cheyunkeji.er.bean.evaluate.EvaluateDetailResult2;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.view.SToast;
import com.google.gson.Gson;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by Michael on 2017/6/1 15:30.
 */

public class TyreCheckFragment extends BaseFragment implements EvaluateWorkflowActivity.OnOutActionListener {
    public static final int PAGE_INDEX = 7;
    private static final String TAG = TyreCheckFragment.class.getSimpleName();
    @BindView(R.id.sv_front_left)
    Switch svFrontLeft;
    @BindView(R.id.sv_front_right)
    Switch svFrontRight;
    @BindView(R.id.iv_car)
    ImageView ivCar;
    @BindView(R.id.sv_behind_left)
    Switch svBehindLeft;
    @BindView(R.id.sv_behind_right)
    Switch svBehindRight;
    @BindView(R.id.tv_previous_step)
    TextView tvPreviousStep;
    @BindView(R.id.tv_next_step)
    TextView tvNextStep;
    private Switch[] swList = null;

    private List<EvaluateDetailResult2.DetectionBean.TireBean> tire;
    private Runnable mTask;

    @Override
    protected void doInflaterView(LayoutInflater inflater, ViewGroup container) {
        contentView = inflater.inflate(R.layout.er_frag_tyre_check, container, false);
        ButterKnife.bind(this, contentView);
    }

    @Override
    protected void init() {
        if (null == swList) {
            swList = new Switch[]{svFrontLeft, svBehindLeft, svFrontRight, svBehindRight};
        }
        if (null != MyApplication.getInstance().getEvaluateResult() && null != MyApplication.getInstance().getEvaluateResult().getDetection() && null != MyApplication.getInstance().getEvaluateResult().getDetection().getTire()) {
            displayInfo();
        }
    }

    @Override
    protected void initView() {
//      设置Switch字体颜色
        svFrontLeft.setSwitchTextAppearance(getActivity(), R.style.switch_text_style2);
        svFrontRight.setSwitchTextAppearance(getActivity(), R.style.switch_text_style2);
        svBehindLeft.setSwitchTextAppearance(getActivity(), R.style.switch_text_style2);
        svBehindRight.setSwitchTextAppearance(getActivity(), R.style.switch_text_style2);

        tvNextStep.setOnClickListener(this);
        tvPreviousStep.setOnClickListener(this);

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void displayInfo() {
        tire = MyApplication.getInstance().getEvaluateResult().getDetection().getTire();
        for (int i = 0; i < tire.size(); i++) {
            swList[tire.get(i).getId() - 1].setChecked(tire.get(i).getStatus() == 1);
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onSaveEvaluateResult(Runnable task) {
        if (task != null) {
            mTask = task;
        }
        if (null == tire) {
            tire = new ArrayList<>();
        } else {
            tire.clear();
        }
        for (int i = 0; i < swList.length; i++) {
            tire.add(new EvaluateDetailResult2.DetectionBean.TireBean(i + 1, swList[i].isChecked() ? 1 : 2));
        }
        Log.e(TAG, "onSaveEvaluateResult: " + new Gson().toJson(tire));
        HashMap<String, String> params = new HashMap<>();
        //      params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
        params.put("aid", MyApplication.getInstance().getEvaluateResult().getAid());
        params.put("detection", new StringBuilder("{\"tire\":").append(new Gson().toJson(tire)).append("}").toString());
        if (MyApplication.getInstance().getEvaluateResult() == null || MyApplication.getInstance().getEvaluateResult().getIroute() == null || MyApplication.getInstance().getEvaluateResult().getIroute().size() == 0) {
            int[] iroute = new int[15];
            iroute[PAGE_INDEX] = 1;
            String json = new Gson().toJson(iroute);
            Log.e(TAG, "saveData: 评估记录为空或数组为空时 保存记录数组 ：  " + json.substring(1, json.length() - 1));
            params.put("iroute", json.substring(1, json.length() - 1));
        } else {
            MyApplication.getInstance().getEvaluateResult().getIroute().set(PAGE_INDEX, 1);
            String json = new Gson().toJson(MyApplication.getInstance().getEvaluateResult().getIroute());
            params.put("iroute", json.substring(1, json.length() - 1));
            Log.e(TAG, "saveData:  保存记录数组 ：记录非空并且数组非空时 保存记录数组 ：   " + json.substring(1, json.length() - 1));
        }
        //        根据评估类型进行保存或编辑
        int evaluateType = ((EvaluateWorkflowActivity) getActivity()).getEvaluateArchiveType();
//       保存新创建、未上传待评估数据
        if (evaluateType == Constants.ARCHIVE_TYPE_CREATE_NEW_EVALUATE || evaluateType == Constants.ARCHIVE_TYPE_UN_UPLOAD_TO_EVALUATE || evaluateType == Constants.ARCHIVE_TYPE_WITH_FAST_EVALUATE_VIN) {
            ApiClient.postForm(((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(), params, new RespCallback<EvaluateDetailResult2>() {
                @Override
                protected void onRequestFailed(String msg) {
                    SToast.show(msg);
                    if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                        mTask.run();
                        mTask = null;
                    }
                }
                @Override
                protected void onSuccess(EvaluateDetailResult2 data) {
                    if (null != data) {
                        MyApplication.getInstance().setEvaluateResult(data);
                        if (mTask != null) {
                            mTask.run();
                            mTask = null;
                        }
                    }
                }
                @Override
                public void onBefore(Request request, int id) {
                    showDialog();
                }
                @Override
                public void onAfter(int id) {
                    dismissDialog();
                }

            });

        } else if (evaluateType == Constants.ARCHIVE_TYPE_UPLOADED_TO_EDIT) {
            ApiClient.postForm(((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(), params, new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    // 网络异常
                    if (e instanceof UnknownHostException || e instanceof SocketException) {
                        SToast.show(R.string.tip_network_error, Gravity.CENTER);
                        return;
                    }
                }

                @Override
                public void onResponse(String response, int id) {
                    try {
                        JSONObject obj = new JSONObject(response);
                        if (obj.optInt("code") == 1) {
                            Log.e(TAG, "onResponse: 编辑成功 : " + obj.optString("data"));
                            if (mTask != null) {
                                mTask.run();
                                mTask = null;
                            }
                        } else {
                            SToast.show( obj.optString("msg") );
                            if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                                mTask.run();
                                mTask = null;
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onBefore(Request request, int id) {
                    showDialog();
                }

                @Override
                public void onAfter(int id) {
                    dismissDialog();
                }
            });
        }
    }

    private void goToPreviousPage() {
        ((EvaluateWorkflowActivity) getActivity()).setCurrentPage(CarLacquerCheckFragment.PAGE_INDEX);
    }

    private void goToNextPage() {
        ((EvaluateWorkflowActivity) getActivity()).setCurrentPage(EngineCabinCheckFragment.PAGE_INDEX);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_previous_step:
                onSaveEvaluateResult(new Runnable() {
                    @Override
                    public void run() {
                        goToPreviousPage();
                    }
                });
                break;
            case R.id.tv_next_step:
                onSaveEvaluateResult(new Runnable() {
                    @Override
                    public void run() {
                        goToNextPage();
                    }
                });
            default:
                break;
        }
    }

}
